package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.dto.SetmealDto;
import com.itheima.pojo.Category;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.CategoryService;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    //新增套餐接口
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        //1.保存套餐数据到setmeal表中
        setmealService.save(setmealDto);
        //2.保存套餐菜品数据到setmeal_dish表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishService.save(setmealDish);
        }
        return R.success("新增成功");
    }

    //套餐分页查询
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        //分页构造器
        Page<Setmeal> pg = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(name != null, Setmeal::getName, name);
        qw.orderByDesc(Setmeal::getUpdateTime);
        setmealService.page(pg, qw);
        long total = pg.getTotal();//获取总条目数
        //获取当页条目数
        List<Setmeal> records = pg.getRecords().stream().map((setmeal) -> {
            //获取Setmeal表里的菜品分类的categoryId
            Long categoryId = setmeal.getCategoryId();
            //获取category对象
            Category category = categoryService.getById(categoryId);
            //获取套餐分类的name
            String categoryName = category.getName();
            //给setmealDto的categoryName设置name
            SetmealDto setmealDto = new SetmealDto();
            setmealDto.setCategoryName(categoryName);
            //将 setmeal 数据放入到 setmealDto 里面
            BeanUtils.copyProperties(setmeal, setmealDto);
            return setmealDto;
        }).collect(Collectors.toList());
        //创建集合
        Map<String, Object> map = new HashMap();
        map.put("total", (Long) total);
        map.put("records", records);
        return R.success(map);
    }

    //删除套餐
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        //条件构造器
        LambdaQueryWrapper<Setmeal> qw1 = new LambdaQueryWrapper<>();
        qw1.in(Setmeal::getId, ids).eq(Setmeal::getStatus, 1);
        //统计满足条件的个数
        int count = setmealService.count(qw1);
        if (count > 0) {
            throw new CustomException("商品售卖中，不能删除");
        }
        setmealService.removeByIds(ids);
        //表里对应的id才能删除
        LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
        qw2.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(qw2);
        return R.success("删除成功");
    }

    //起售停售
    @PostMapping("/status/{status}")
    public R<String> get(@PathVariable int status, @RequestParam List<Long> ids) {
        //update ruiji set status = ? where id in (1,2,3);
        for (Long id : ids) {
            Setmeal setmeal = setmealService.getById(id);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("操作成功");
    }

    //(回显) 前台
    @GetMapping("/list")
    public R<List<SetmealDto>> updateAll(Long categoryId,Integer status) {
        //1、根据套餐id查询套餐数据 select * from setmeal where id =?
        LambdaQueryWrapper<Setmeal> qw1 = new LambdaQueryWrapper<>();
        qw1.eq(Setmeal::getCategoryId, categoryId);

        qw1.eq(Setmeal::getStatus,status);
        List<SetmealDto> setmealList = setmealService.list(qw1).stream().map((setmeal)->{
            Long id = setmeal.getId();
            //2、根据套餐id查询套餐对应的菜品数据 select * from setmeal_dish where setmeal_id = ?
            LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
            qw2.eq(SetmealDish::getSetmealId, id);
            List<SetmealDish> setmealDishList = setmealDishService.list(qw2);
            //3. 首先new一个SetmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //4.拷贝 setmeal 到 setmealDto 中
            BeanUtils.copyProperties(setmeal, setmealDto);
            //5.将setmealDishList数据注入到setmealDto
            setmealDto.setSetmealDishes(setmealDishList);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealList);
    }

    //(回显) 后台
    @GetMapping("/{id}")
    public R<SetmealDto> update(@PathVariable Long id){
        //1.通过套餐id获取套餐数据，拷贝到DTO
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal,setmealDto);
        //2.通过套餐id，获取套餐内菜品
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> list = setmealDishService.list(qw);
        //3.菜品数据封装到DTO中
        setmealDto.setSetmealDishes(list);
        return R.success(setmealDto);
    }

    //修改套餐
    @PutMapping
    public R updateById(@RequestBody SetmealDto setmealDto) {
        //1.修改基本数据，update setmeal set xx = ?, where id = ?;
        setmealService.updateById(setmealDto);
        //2.清理套餐分类下的数据
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, setmealDto.getId());
        //3.先根据套餐id删除套餐对应的菜品数据：
        //delete from setmeal_dish where setmeal_id =?
        setmealDishService.remove(qw);
        //4.获取套餐里的数据，归属对应的id
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //5.保存套餐分类下的数据
        return R.success(setmealDishes);
    }
}
